<script setup>
import HeaderDemo from '../components/HeaderDemo.vue';
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

// 导入 Element Plus 的组件
import { ElDialog, ElForm, ElFormItem,ElNotification , ElInput, ElSelect, ElOption, ElButton } from 'element-plus';

const showModal = ref(false);
const openModal = () => { showModal.value = true; };
const closeModal = () => { showModal.value = false; };

const scripts = ref([]);
const randomScripts = ref([]);
const submissions = ref([]);
const router = useRouter();
const selectedCategory = ref('');

// 用户输入内容集中在 formData 中
const formData = ref({
  title: '',
  description: '',
  category: '',
  publisher: '',
  fileName: '' // 用于存储用户输入的内容
});

// 提交发布信息的函数
const submitSubmission = async () => {
  const currentDate = new Date().toISOString();

  // 构建要发送的数据对象
  const payload = {
    ...formData.value,
    publishDate: currentDate,
  };

  try {
    // 通过 API 将数据发送到后端
    const response = await axios.post('http://localhost:8080/submissions/publish', payload);
    console.log('发布成功:', response.data);
    ElNotification({
      title: '成功',
      message: '发布成功！',
      type: 'success',
      duration: 2000
    });

    // 清空输入框内容，关闭模态框，并刷新列表
    closeModal();
    formData.value = {
      title: '',
      description: '',
      category: '',
      publisher: '',
      fileName: ''
    };
    await fetchSubmissions();
  } catch (error) {
    console.error('发布失败:', error);
    ElNotification({
      title: '错误',
      message: '发布失败，请重试',
      type: 'error',
      duration: 2000
    });
  }
};

// 过滤后的 submissions，只显示符合 selectedCategory 的项目
const filteredSubmissions = computed(() => {
  if (selectedCategory.value === '') {
    return submissions.value; // 显示所有分类
  }
  return submissions.value.filter(item => item.category === selectedCategory.value);
});

// 切换分类的方法
const selectCategory = (category) => {
  selectedCategory.value = category;
};

const goToDetail = (id) => {
  console.log('正在跳转的 ID:', id);
  if (id) {
    router.push({ name: 'SolicitDetail', params: { id: id } });
  } else {
    console.error('未提供有效的 ID 参数');
  }
};

const navigateToWork = (wid) => {
  router.push({ path: `/workprofile/${wid}` }).then(() => {
    window.location.reload();
  });
};

const truncateText = (text, maxLength = 20) => {
  return text.length > maxLength ? text.slice(0, maxLength) + '...' : text;
};

const formatDate = (dateString) => {
  const date = new Date(dateString);
  return date.toLocaleString();
};

const selectRandomScripts = () => {
  if (scripts.value.length <= 5) {
    randomScripts.value = scripts.value;
    console.log("Random scripts (all):", randomScripts.value);
    return;
  }

  const selected = new Set();
  while (selected.size < 5) {
    const randomIndex = Math.floor(Math.random() * scripts.value.length);
    selected.add(scripts.value[randomIndex]);
  }
  randomScripts.value = Array.from(selected);
  console.log("Random scripts (selected):", randomScripts.value);
};

const fetchSubmissions = async () => {
  try {
    const response = await axios.get('http://localhost:8080/submissions/all');
    console.log("Submissions API response:", response.data);

    if (response.data) {
      submissions.value = response.data.map(item => {
        console.log("Loaded submission item:", item); // 打印每个项目的数据
        return {
          id: item.id, // 确保从响应中获取 id
          category: item.category,
          title: item.title,
          description: item.description,
          publishDate: item.publishDate,
          publisher: item.publisher,
          fileName: item.fileName
        };
      });
      console.log("%%%%Submissions loaded:", submissions.value);
    } else {
      console.error("%%%Unexpected data structure:", response.data);
    }
  } catch (error) {
    console.error("%%%Error fetching submissions:", error);
  }
};

const submit = () => {
  // 在这里执行你的业务逻辑，例如提交表单数据
  console.log('提交表单');
};

const fetchScripts = async () => {
  try {
    const response = await axios.get('http://localhost:8080/api/getworklist');
    console.log("API response:", response.data);

    if (response.data && response.data.data) {
      scripts.value = response.data.data.flatMap(item => item.data);
      console.log("Scripts loaded:", scripts.value);
      selectRandomScripts();
    } else {
      console.error("Unexpected data structure:", response.data);
    }
  } catch (error) {
    console.error("Error fetching scripts:", error);
  }
};

fetchScripts();
fetchSubmissions();
</script>


<template>
  <el-header class="header">
    <HeaderDemo />
  </el-header>
  <div class="container">
    <div class="card">
      <div class="category">
        <div class="button-group">
          <div class="buttons">
  <button @click="selectCategory('')">全部</button>
  <button @click="selectCategory('剧本征集')">剧本征集</button>
  <button @click="selectCategory('剧本出售')">剧本出售</button>
  <button @click="selectCategory('版权出售')">版权出售</button>
  <button @click="selectCategory('项目合作')">项目合作</button>
  <button @click="selectCategory('其他')">其他</button>
</div>
<el-button type="primary" @click="openModal" class="publish-button">发布</el-button>
        </div>
      </div>
      <!-- 发布模态框 -->
<el-dialog title="发布信息" v-model="showModal" width="900px" @close="closeModal">

  <el-form :model="formData" label-width="100px">
    <el-form-item label="标题">
      <el-input v-model="formData.title" placeholder="请输入标题"></el-input>
    </el-form-item>

    <el-form-item label="描述">
      <el-input type="textarea" v-model="formData.description" placeholder="请输入描述"></el-input>
    </el-form-item>

    <el-form-item label="分类">
      <el-select v-model="formData.category" placeholder="请选择分类">
        <el-option label="剧本征集" value="剧本征集"></el-option>
        <el-option label="剧本出售" value="剧本出售"></el-option>
        <el-option label="版权出售" value="版权出售"></el-option>
        <el-option label="项目合作" value="项目合作"></el-option>
        <el-option label="其他" value="其他"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="发布者">
      <el-input v-model="formData.publisher" placeholder="请输入发布者姓名"></el-input>
    </el-form-item>

    <el-form-item label="内容">
      <el-input type="textarea" v-model="formData.fileName" placeholder="请输入内容":autosize="{ minRows: 4, maxRows: 10 }"></el-input>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitSubmission">发布</el-button>
      <el-button @click="closeModal">取消</el-button>
    </el-form-item>
  </el-form>
</el-dialog>


      
      <div class="submission-list">
        <div class="submission-item" v-for="(submission, index) in filteredSubmissions " :key="index" @click="goToDetail(submission.id)">
          <h3>【{{ submission.category }}】{{ submission.title }}</h3>
          <p>{{ submission.description }}</p>
          <p class="date">发布时间：{{ formatDate(submission.publishDate) }}&nbsp;&nbsp;&nbsp;&nbsp;发布方：{{ submission.publisher }}</p>
        </div>
      </div>
    </div>
    
    <div class="side-card">
      <!-- <div class="side"> -->
        <img src="../../public/images/_20241114052052.png" alt="" style="width: 250px;height: 340px; margin-right: 80px;">
      <!-- </div> -->
      <div class="bottom-card">
        <h3>推荐剧本</h3>
        <div class="script-cards">
          <div v-for="(script, index) in randomScripts" :key="script"  @click="navigateToWork(script.wid)" class="script-card">
            <img :src="'http://localhost:8080/api/images/' + script.wimage" alt="封面图片" class="cover-image" />
            <div class="content">
              <h4> {{ script.wname || '无标题' }}</h4>
              <p> {{ truncateText(script.introduction || '暂无简介') }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>


<style scoped>
.header {
  background-color: #020202;
  height: 80px;
  padding: 1px;
}
.container {
    display: flex;
}
  .card {
    flex: 1;
    width: 100px;
    margin-left: auto;
    margin-top: 20px;
    min-width: 1000px;
    max-width: 300px;
    min-height: 900px;
    padding: 20px;
    border: 1px solid #ffffff;
    border-radius: 10px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    background-color: #f4f4f4;
  }
  .side-card {
  width: 250px;
  height: auto;
  margin-right: auto;
  margin-left: 30px;
  margin-top: 20px;
  background-color: #ffffff;
}

.side {
  width: 250px;
  height: 350px;
  margin-left: 1px;
  margin-top: 1px;
  background: linear-gradient(to bottom, #fffff3, #d8d8d8); /* 古风渐变背景 */
  border-radius: 10px; /* 设置圆角 */
  box-shadow: 0 4px 6px rgba(177, 174, 174, 0.2); /* 添加阴影以增强卡片效果 */
  padding: 16px; /* 内边距，让内容不紧贴边框 */
}
.bottom-card {
  width: 250px;
  height: auto;
  margin-left: 1px;
  margin-top: 20px;
  background-color: #F7F7F7;
  /* background: linear-gradient(135deg, #fffff3, #ffffff); */
  border-radius: 10px; /* 设置圆角 */
  box-shadow: 0 4px 6px rgba(177, 174, 174, 0.2); /* 添加阴影以增强卡片效果 */
  padding: 16px; /* 内边距，让内容不紧贴边框 */
  color: rgb(177, 177, 177); /* 设置字体颜色，使文本在绿色背景上清晰 */
  font-family: Arial, sans-serif; /* 设置字体 */
}
.script-cards {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.script-card {
  display: flex;
  align-items: center;
  width: 220px; /* 卡片的固定宽度 */
  height: 100px; /* 卡片的固定高度 */
  background-color: #F7F7F7;
  padding: 10px;
  border-radius: 8px;
}
.script-card:hover {
  background-color: #ffffff; /* 悬停时的背景颜色 */
}

.cover-image {
  width: 70px; /* 封面图片宽度 */
  height: 70px; /* 封面图片高度 */
  object-fit: cover; /* 保持图片的比例 */
  margin-right: 10px; /* 图片与文字内容之间的间距 */
  border-radius: 5px;
}

.content {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.content h4 {
  font-size: 1em;
  color: #333;
  /* margin: 0 0 5px 0; */
  font-family: 'Microsoft YaHei', sans-serif; /* 使用微软雅黑 */
}

.content p {
  font-size: 0.9em;
  color: #666;
  margin: 0;
  font-family: 'Microsoft YaHei', sans-serif; /* 使用微软雅黑 */
}



  .category {
    margin-bottom: 20px;
    padding: 15px;
    border: 1px solid #ccc;
    border-radius: 8px;
  }

  .button-group {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .buttons {
    display: flex;
    gap: 10px;
  }

  .buttons button {
    padding: 10px 15px;
    font-size: 1em;
    color: #fff;
    background-color: #9ec9f7;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s;
  }

  .buttons button:hover {
    background-color: #d8dadc;
  }

  .publish-button {
    padding: 10px 15px;
    font-size: 1em;
    color: #fff;
    background-color: #28a745;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s;
  }

  .publish-button:hover {
    background-color: #218838;
  }
   /* 弹出窗口的遮罩层 */
   .modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
  }

  /* 弹出窗口的内容区域 */
  .modal-content {
    background-color: #fff;
    padding: 20px;
    border-radius: 10px;
    width: 400px;
    max-width: 90%;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  }

  .modal-content h2 {
    margin-top: 0;
  }

  .modal-content form {
    display: flex;
    flex-direction: column;
  }

  .modal-content label {
    margin-top: 10px;
  }

  .modal-content input,
  .modal-content textarea,
  .modal-content select {
    margin-top: 5px;
    padding: 8px;
    font-size: 1em;
    border: 1px solid #ccc;
    border-radius: 5px;
  }

  .modal-content button {
    margin-top: 15px;
    padding: 10px;
    font-size: 1em;
    cursor: pointer;
    border: none;
    border-radius: 5px;
    transition: background-color 0.3s;
  }

  .modal-content button[type="submit"] {
    background-color: #28a745;
    color: #fff;
  }

  .modal-content button[type="submit"]:hover {
    background-color: #218838;
  }

  .modal-content button[type="button"] {
    background-color: #dc3545;
    color: #fff;
  }

  .modal-content button[type="button"]:hover {
    background-color: #c82333;
  }

  .submission-item {
    margin-bottom: 20px;
    padding: 15px;
    border: 1px solid #ccc;
    border-radius: 8px;
    cursor: pointer;
  }

  .submission-item h3 {
    font-size: 1.2em;
    color: #006600;
  }

  .submission-item p {
    font-size: 1em;
    color: #333;
  }

  .submission-item .date {
    font-size: 0.9em;
    color: #999;
  }
</style>



